package com.jtech.together.view.weight.popup;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jtech.together.R;
import com.jtech.together.util.AudioPlayer;
import com.jtech.together.util.Util;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 音频播放器
 * Created by hasee on 2017/4/28.
 */

public class AudioPlayerPopup implements PopupWindow.OnDismissListener, AudioPlayer.OnPlayerListener {
    @Bind(R.id.textview_voice_player_progress)
    TextView textViewProgress;
    @Bind(R.id.progressbar_voice_player_progress)
    ProgressBar progressBar;

    private PopupWindow popupWindow;
    private AudioPlayer audioPlayer;

    public AudioPlayerPopup(Context context) {
        //初始化popup
        popupWindow = new PopupWindow(context);
        //实例化视图
        View contentView = LayoutInflater.from(context)
                .inflate(R.layout.view_voice_player, null, false);
        //绑定视图注解注入
        ButterKnife.bind(this, contentView);
        //实例化播放器
        audioPlayer = new AudioPlayer(progressBar);
        //设置主视图
        popupWindow.setContentView(contentView);
        //设置popup参数
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOnDismissListener(this);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setAnimationStyle(0);
        popupWindow.setFocusable(false);
        //监听播放器进度
        audioPlayer.setOnPlayerListener(this);
    }

    /**
     * 构造popup
     *
     * @param context
     * @return
     */
    public static AudioPlayerPopup build(Context context) {
        return new AudioPlayerPopup(context);
    }

    /**
     * 播放url
     *
     * @param audioUrl
     * @return
     */
    public AudioPlayerPopup setAudioUrl(String audioUrl) {
        audioPlayer.playUrl(audioUrl);
        return this;
    }

    /**
     * 显示popup
     *
     * @param parent
     */
    public PopupWindow showAsDropDown(View parent) {
        popupWindow.showAsDropDown(parent);
        return popupWindow;
    }

    @Override
    public void onProgress(int current, int duration) {
        textViewProgress.setText(Util.formatMediaLength(current) + "-" + Util.formatMediaLength(duration));
    }

    @Override
    public void onCompletion() {
        popupWindow.dismiss();
    }

    /**
     * 关闭播放器
     */
    @OnClick(R.id.imagebutton_voice_player_close)
    public void onCloseClick() {
        popupWindow.dismiss();
    }

    @Override
    public void onDismiss() {
        //在销毁pop的时候自动关闭音频播放器
        audioPlayer.stop();
    }
}